package com.leixiaoqiao.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取子类的字节码文件
        Class<? extends BaseServlet> aClass = this.getClass();
        //获取调用子类方法的名称
        String method = req.getParameter("method");
        //判断前端传递的方法名是否为空
        if (method==null||"".equals(method)){
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.write("请求地址不合法，不能处理你的请求，请检查你的地址");
            pw.close();
            return;
        }
        //如果不为空，根据方法名反射调用子类方法
        try{
            Method childMethod = aClass.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            childMethod.invoke(this,req,resp);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("反射调用出现异常，请检查子类是否有对应方法或者其他");
        }
    }
}
